package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author by Dragon
 * @Classname ${NAME}
 * @Description TODO
 * @Date 2020/2/24 17:26
 * @Version 1.0
 */
public class HtmlFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        if (request.getRequestURI().endsWith("/login.html")) {
            chain.doFilter(request, response);
        } else {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (name.equals("JSESSIONID")) {
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }
            response.sendRedirect("/pages/login.html");
        }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}
